<?php

declare(strict_types=1);

namespace app\yperp\command;


use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\yperp\model\Supplier as SupplierModel;
use app\yperp\common\ChanghongList;
use app\yperp\common\ExcelTools;
use app\yperp\common\Redis;
use app\yperp\job\MgtJob;
use app\yperp\job\MgtJobImage;
use app\yperp\job\MgtJobType;
use think\Db;
use think\Model as ThinkModel;
use think\Queue;


class upload extends Command
{

    protected $output;

    protected $input;
    protected $driver;
    protected $windows = [];
    protected $cookies = [];
    protected function configure()
    {
        // 指令配置
        $this->setName('upload')
            ->setDescription('the urltest command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $this->input = $input;

        $this->output = $output;


        $goods_files = scandir(env('root_path') . 'runtime' . DIRECTORY_SEPARATOR . 'goods');

        foreach ($goods_files as $goods_file) {
            if ($goods_file !== '.' && $goods_file !== '..') {
                $goods_file = env('root_path') . 'runtime' . DIRECTORY_SEPARATOR . 'goods' . DIRECTORY_SEPARATOR . $goods_file;

                $res =  self::saveData($goods_file);
            }
        }
    }


    static public function uploadfile($file_path = null)
    {

        $goods_code = pathinfo($file_path, PATHINFO_FILENAME);

        // 删除文件后缀名（假设后缀名是以点号开头，后跟一个或多个字母）
        $goods_code = preg_replace('/\.\w+$/', '', $goods_code);

        $goods_code = Pinyin('permalink', $goods_code, '_');

        $extractToDir = env('root_path') . 'public' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'goods' . DIRECTORY_SEPARATOR . $goods_code;

        isdir($extractToDir);

        // 打开 ZIP 文件
        $zipFile = new \PhpZip\ZipFile();
        $zipFile->openFile($file_path); // open archive from file

        $listFiles = $zipFile->getListFiles();
        $zip_one_dir =    explode('/', $listFiles[0])[0];

        $zipFile->extractTo($extractToDir); // extract files to the specified directory
        $zipFile->close();;

        moveFilesToDirectory($extractToDir . DIRECTORY_SEPARATOR . $zip_one_dir, $extractToDir);
        rmdir($extractToDir . DIRECTORY_SEPARATOR . $zip_one_dir);

        // 遍历数组中的每个文件名
        $excelFiles = '';
        foreach ($listFiles as $file) {
            // 使用字符串函数检查文件扩展名
            if (strpos($file, '.xls') !== false || strpos($file, '.xlsx') !== false) {
                // 如果文件名包含 .xls 或 .xlsx，则添加到结果数组中
                $excelFiles = $extractToDir . DIRECTORY_SEPARATOR . $file;
            }
        }

        $excelFiles = str_replace(DIRECTORY_SEPARATOR . $zip_one_dir, '', $excelFiles);

        return [$excelFiles, $goods_code];
    }





    static public function saveData($file_path)
    {
        list($excelFiles, $goods_code) = self::uploadfile($file_path);
        // dump($excelFiles, $goods_code);
        // $datas = ExcelTools::getData($excelFiles, 0, 1, [
        //     'corp_name' => '供应商名称',
        //     'goods_code' => '资料编码',
        //     'goods_title' => '商品名称',
        //     'goods_title_alias' => '商品名称',
        //     'goods_color' => '颜色',
        //     'goods_color_alias' => '颜色',
        //     'goods_color_id' => '颜色id',
        //     'goods_specs' => '规格',
        //     'goods_sku' => '商品编码',
        //     'goods_sku_alias' => '商品编码别名',
        //     'goods_in_price' => '供货价',
        //     'goods_buy_price' => '零售价',
        //     'goods_retail_price' => '分销控价',
        //     'goods_buy_number' => '库存',
        // ]);

        // // 启动事务
        // Db::startTrans();
        // try {

        //     foreach ($datas as $key => $data) {
        //         $corp_name =    $data['corp_name'];
        //         unset($data['corp_name']);
        //         $corp =  Db::name('yperp_corp')->where(['corp_name' => $corp_name])->find();
        //         if (!$corp) {
        //             Db::name('yperp_corp')->insert(['corp_name' => $corp_name]);
        //         }

        //         $data['goods_color_id'] = $key + 1;

        //         $where = [
        //             'corp_id' => $corp['id'],
        //             'goods_code' => $data['goods_code'],
        //             'goods_sku' => $data['goods_sku'],
        //         ];

        //         $data['goods_code_alias'] = $goods_code;

        //         $data['goods_sku_alias'] = 'csmb_' . strTools($data['goods_sku']);

        //         $isset = Db::name('yperp_supplier')->where($where)->find();
        //         if ($isset) {
        //             // SupplierModel::where(['id' => $isset['id']])->update($data);
        //         } else {
        //             // SupplierModel::create($data);
        //         }
        //     }
        //     Db::commit();
        //     return true;
        // } catch (\Throwable $th) {
        //     Db::rollback();
        //     dump($th->getMessage());
        //     dump($th->getTraceAsString());
        //     return false;
        // }
    }
}
